package org.pay.pay.service;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.pay.pay.mq.Mq4TransNotify;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.pay.core.common.util.MyLog;
import org.pay.core.common.util.RpcUtil;
import org.pay.core.entity.TransOrder;
import org.pay.pay.mq.BaseNotify4MchTrans;

import java.util.HashMap;
import java.util.Map;

/**
 * @author: yangshancheng
 * @date: 17/10/30
 * @description:
 */
@Service
public class TransOrderService {

    private static final MyLog _log = MyLog.getLog(TransOrderService.class);

    @Autowired
    private RpcCommonService rpcCommonService;

    @Autowired
    private Mq4TransNotify mq4TransNotify;

    @Autowired
    private BaseNotify4MchTrans baseNotify4MchTrans;

    public int create(JSONObject transOrder) {
        Map<String,Object> paramMap = new HashMap<>();
        paramMap.put("transOrder", transOrder);
        String jsonParam = RpcUtil.createBaseParam(paramMap);
        Map<String, Object> result = rpcCommonService.rpcTransOrderService.create(jsonParam);
        String s = RpcUtil.mkRet(result);
        if(s == null) return 0;
        return Integer.parseInt(s);
    }

    public void sendTransNotify(String transOrderId, String channelType) {
        JSONObject object = new JSONObject();
        object.put("transOrderId", transOrderId);
        object.put("channelType", channelType);
        mq4TransNotify.send(object.toJSONString());
    }

    public JSONObject query(Long mchId, String transOrderId, String mchTransNo, String executeNotify) {
        TransOrder transOrder;
        if(StringUtils.isNotBlank(transOrderId)) {
            transOrder = rpcCommonService.rpcTransOrderService.baseSelectByMchIdAndTransOrderId(mchId, transOrderId);

        }else {
            transOrder = rpcCommonService.rpcTransOrderService.baseSelectByMchIdAndMchTransNo(mchId, mchTransNo);
        }
        if(transOrder == null) return null;
        boolean isNotify = Boolean.parseBoolean(executeNotify);
        if(isNotify) {
            baseNotify4MchTrans.doNotify(transOrder, false);
            _log.info("业务查单完成,并再次发送业务转账通知.发送完成");

        }
        return (JSONObject) JSONObject.toJSON(transOrder);
    }

}
